package com.pine.sort.impl;

import com.alibaba.fastjson.JSON;
import com.pine.common.EfficiencyTest;
import com.pine.common.GeneratorArr;
import com.pine.sort.ISort;

import java.lang.reflect.InvocationTargetException;

/**
 * 选择排序实现类
 * 从最小值开始
 * [0-i)顺序，[i-n)为乱序
 */
public class SelectionSort implements ISort {
    @Override
    public <E extends Comparable<E>> E[] sort(E[] eArr) {
        // 迭代出最小值
        for (int i = 0; i < eArr.length; i++) {
            E temE = eArr[i];
            int minIndex = i;
            // 与之后的所有元素相比较
            for (int j = i + 1; j < eArr.length; j++) {
                // 找出最小值，然后与下标i交换值
                if (temE.compareTo(eArr[j]) > 0) {
                    temE = eArr[j];
                    minIndex = j;
                }
            }
            ISort.swap(eArr, i, minIndex);
        }
        return eArr;
    }

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        int length = 100;
        int testNum = 1000000;
        SelectionSort selectionSort = new SelectionSort();
        Integer[] dataArr = GeneratorArr.outOfOrderDistinctIntegerArr(length);
        double time = EfficiencyTest.nanoTime(testNum, selectionSort, dataArr);
        System.out.println(JSON.toJSONString(time));
    }
}
